import { useState, useRef } from 'react'
import { Button, message, Modal, Input, Tag } from 'antd'
import { ProTable } from '@ant-design/pro-components'
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import AddEdit from '../AddEdit'
import { RemoveParamsFnc, AddDelParamsFnc } from '@/services/params'
import useSyncState from '@/utils/tongbu'


const Tables = ({btnDisabled, activeName, dataSource, cascaderValue, catID, getTable}: any) => {
  const [modal, contextHolder] =  Modal.useModal()
  const [messageApi, contextHolderB] = message.useMessage()
  const [pageSize, setPageSize] = useState(2) // table 每页显示的条数
  const [isModalOpen, setIsModalOpen] = useState(false); // 添加修改用户的盒子
  const [openType, setOpenType] = useState(''); // 要么是add 要么是edit 打开盒子传值 关闭盒子不传值
  const [attrID, setAttrID] = useState('') // attrID 打开编辑盒子使用
  const [iptVisible, setIptVisible] = useSyncState(false) // tag ipt显示还是隐藏
  const iptRef = useRef<any>(null)

  // 打开添加 修改 用户盒子 给子组件使用
  const openBox = (flag: boolean, ...args: any[]) => {
    setIsModalOpen(flag)
    setOpenType(args[0])
    setAttrID(args[1])
  }

  // 删除动态参数 或者 静态属性
  const deleteParamsAttr = (record: {attr_id: number}) => {
    modal.confirm({
    icon: <ExclamationCircleOutlined />,
    content: '此操作将永久删除用户, 是否继续?',
    onOk: async () => {
        const res = await RemoveParamsFnc(parseInt(catID), record.attr_id)
        if (res.meta.status === 200) {
        message.open({
            type: 'success',
            content: '删除成功',
            duration: 1.5,
            onClose: () => {
            getTable(cascaderValue, activeName)
            },
        });
        }
    },
    });
  }


  // 添加删除 tag公共方法
  const publicAddDel = async (record: any, msg: string) => {
    const res = await AddDelParamsFnc(record.cat_id, record.attr_id, {
      attr_name: record.attr_name,
      attr_sel: record.attr_sel,
      attr_vals: record.attr_vals
    })
    if(res.meta.status === 200) {
       messageApi.success(msg, 0.5)
    }
  }

  // 删除tag标签
  const tagClose = (record: any, index: number) => {
    let arr = record.attr_vals.trim().split(" ")
    arr.splice(index, 1).join(' ')
    let arrB = arr.join(' ')
    record.attr_vals = arrB
    publicAddDel(record, '删除成功')
  }

  // 添加tag标签 并隐藏input
  const hideIpt = async (e:any , record: any) => {
    setIptVisible(false)
    if(e.target.value !== '') {
      record.attr_vals = record.attr_vals.concat(' ' + e.target.value)
      publicAddDel(record, '添加成功')
    }
  }

  // 显示ipt
  const showIpt = () => {
    setIptVisible(true, () => {
      iptRef.current.focus()
    })
  }
  
  // 要么是ipt显示 要么是btn显示
  const showBtnTags = (record: any) => {
    if(iptVisible) {
      return <Input ref={iptRef} style={{width: '150px'}} onBlur={(e) => hideIpt(e, record)}/>
    } else{
      return <Button onClick={() => showIpt()}>+ new Tag</Button>
    }
  }

  // 显示 tag标签
  const subTags = (record: any) => {
    if(record.attr_vals !== '') {
      return record.attr_vals.trim().split(' ').map((item: number, index: number) => {
        return <Tag color='blue' key={index} closable onClose={() => tagClose(record, index)}>{item}</Tag>
      })
    } 
  }

  const columns: any = [
    {title: '商品名称', dataIndex: 'attr_name', key: 'goods_name', width: 400, ellipsis: true},
    {title: '操作', width: 180, render: (record: {attr_id: number}) => {
     return (
       <>
        <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => openBox(true, 'edit', record.attr_id)}>编辑</Button> 
        <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteParamsAttr(record)} style={{margin: '0 6px 0'}}>删除</Button> 
       </>
     )
    }}
  ]      

  return (
    <>
      {contextHolder}
      {contextHolderB}
      <ProTable columns={columns}
        rowKey={(record: {attr_id: number}) => record.attr_id}
        dataSource={dataSource}
        scroll={{ x: 500 }}
        bordered
        search={false}
        toolbar={{
          actions: [ <Button type="primary" disabled={btnDisabled} onClick={() => openBox(true, 'add')}>{activeName === 'many' ? '添加参数' : '添加属性'}</Button>]
        }}
        pagination={{pageSize: pageSize, showSizeChanger: true, pageSizeOptions: [2, 5, 10],onShowSizeChange: (_: any, size: number) => setPageSize(size)}} 
        expandable={{
           expandedRowRender:(record) => ( <>{subTags(record)} {showBtnTags(record)}</>),
        }}
      />

      <AddEdit attrID={attrID} cascaderValue={cascaderValue} getTable={getTable} catID={catID} isModalOpen={isModalOpen} activeName={activeName} openType={openType} openBox={openBox}/>
    </>
  )
}

export default Tables